package com.chinasoft.demo;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class ExecutorConfig {

	private static final Logger logger=LoggerFactory.getLogger(ExecutorConfig.class);
	
	@Value("${async.executor.thread.core_pool_size}")
	private int corePoolSize;
	
	@Value("${async.executor.thread.max_pool_size}")
	private int maxPoolSize;
	
	@Value("${async.executor.thread.queue_capacity}")
	private int queueCapacity;

	@Bean(name="asyncServiceExecutor")
	public Executor asyncServiceExecutor() {
		logger.info("start asyncServiceExecutor");
		//ThreadPoolTaskExecutor threadPoolTaskExecutor=new ThreadPoolTaskExecutor();
		ThreadPoolTaskExecutor threadPoolTaskExecutor=new VisiableThreadPoolTaskExecutor();
		threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
		threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
		threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
		threadPoolTaskExecutor.setThreadNamePrefix("async-service-");
		//ThreadPoolExecutor.CallerRunsPolicy：由调用线程处理该任务 
		threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		threadPoolTaskExecutor.initialize();
		return threadPoolTaskExecutor;
	}
}
